<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>上传PPT课件</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入PPT标题"></el-input>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科" filterable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校（不选则所有学校可见）" filterable clearable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标签">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleTagClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
          <div class="tag-tip">添加标签可以帮助其他用户更好地找到您的PPT</div>
        </el-form-item>
        
        <el-form-item label="封面图">
          <el-upload
            class="cover-uploader"
            action="#"
            :http-request="uploadCover"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
          >
            <img v-if="form.coverUrl" :src="form.coverUrl" class="cover">
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议上传16:9比例图片，大小不超过2MB</div>
        </el-form-item>
        
        <el-form-item label="PPT文件" prop="fileUrl">
          <el-upload
            class="file-uploader"
            action="#"
            :http-request="uploadFile"
            :before-upload="beforeFileUpload"
            :file-list="fileList"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持各种格式文件，大小不超过50MB</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="内容描述" prop="description">
          <el-input 
            type="textarea" 
            :rows="5" 
            v-model="form.description" 
            placeholder="请输入PPT内容描述，让其他用户了解PPT的内容和用途"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">立即上传</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addPPT } from '@/api/ppt';
import { getAllSubjects } from '@/api/subject';
import { getAllSchools } from '@/api/school';
import { uploadFile as uploadFileAPI, uploadCover as uploadCoverAPI } from '@/api/upload';

export default {
  name: 'PPTUpload',
  data() {
    return {
      form: {
        title: '',
        subjectId: undefined,
        educationLevel: undefined,
        schoolId: undefined,
        description: '',
        tags: '',
        coverUrl: '',
        fileUrl: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        fileUrl: [
          { required: true, message: '请上传PPT文件', trigger: 'change' }
        ]
      },
      subjectOptions: [],
      schoolOptions: [],
      loading: false,
      fileList: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    };
  },
  created() {
    this.getSubjects();
    this.getSchools();
  },
  methods: {
    getSubjects() {
      getAllSubjects().then(response => {
        this.subjectOptions = response.data.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
      });
    },
    getSchools() {
      getAllSchools().then(response => {
        this.schoolOptions = response.data.map(school => ({
          value: school.id,
          label: school.name
        }));
      });
    },
    handleTagClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue && this.dynamicTags.indexOf(inputValue) === -1) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    beforeCoverUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('封面图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('封面图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    uploadCover(options) {
      const { file } = options;
      this.loading = true;
      uploadCoverAPI(file)
        .then(response => {
          this.form.coverUrl = response.data.url;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传封面图片失败');
        });
    },
    beforeFileUpload(file) {
      // 暂时移除文件类型检查，仅保留大小检查
      console.log('文件信息:', file.name, file.type, file.size);
      
      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isLt50M) {
        this.$message.error('文件大小不能超过 50MB!');
      }
      return isLt50M;
    },
    uploadFile(options) {
      const { file } = options;
      this.loading = true;
      uploadFileAPI(file)
        .then(response => {
          this.form.fileUrl = response.data.url;
          this.loading = false;
          this.fileList = [{
            name: file.name,
            url: response.data.url
          }];
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传PPT文件失败');
        });
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.fileUrl) {
            this.$message.error('请上传PPT文件');
            return;
          }
          
          // 处理标签
          this.form.tags = this.dynamicTags.join(',');
          
          this.loading = true;
          addPPT(this.form)
            .then(() => {
              this.$message({
                message: '上传成功',
                type: 'success'
              });
              this.loading = false;
              this.goBack();
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                message: '上传失败',
                type: 'error'
              });
            });
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.form.coverUrl = '';
      this.form.fileUrl = '';
      this.fileList = [];
      this.dynamicTags = [];
    },
    goBack() {
      this.$router.push('/ppt-center');
    }
  }
};
</script>

<style scoped>
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.cover {
  width: 178px;
  height: 100px;
  display: block;
  object-fit: cover;
}
.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.tag-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}
</style> 